package com.yike.user.lkl.incoming.request;

import lombok.Data;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

@Data
public class IncomingFiles {

    private File file;
    private String imgType; // 图片类型 参见 拓客saas文档  附录 【附件类型表】
    private String sourcechnl; // 来源 0:PC,1:安卓,2:IOS
    private Boolean isOcr = false; //是否需要ocr	默认传false
    private String  fileName;


    public IncomingFiles(String url, String  imgType, String sourcechnl, String fileName) throws Exception {
        this.file = urlToFile(url,fileName);
        this.imgType = imgType;
        this.sourcechnl = sourcechnl;
        this.isOcr = false;
        this.fileName = fileName;
    }


    public static File urlToFile(String urlString,String fileName) throws Exception {
        URL url = new URL(urlString);
        int lastDotIndex = fileName.lastIndexOf('.');

        // 创建临时文件
        Path tempPath = Files.createTempFile("download-", "." + fileName.substring(lastDotIndex + 1).toLowerCase());
        File tempFile = tempPath.toFile();

        // 下载内容到临时文件
        try (InputStream in = url.openStream()) {
            Files.copy(in, tempPath, StandardCopyOption.REPLACE_EXISTING);
        }

        // 设置程序退出时删除临时文件
        tempFile.deleteOnExit();

        return tempFile;
    }

}
